<?php
/**
* @package           mod_jstats_counters - Counters for 'Joomla Stats'
*  project homepage  http://www.JoomlaStats.org
* @copyright         Copyright (C) 2005-2008 JoomlaStats Team
* @license           GNU/GPL, see http://www.gnu.org/copyleft/gpl.html.
*/

defined('_JEXEC') or die ('Direct Access to this location is not allowed.');


class modJStatsCounters
{
  function getCountersDefinitions()
  {
	require_once(JPATH_ADMINISTRATOR .DS. 'components' .DS. 'com_joomlastats' .DS. 'database' .DS. 'db.constants.php');

    /* Get DateStamps */
    // might want to use JoomlaStats time offset
    //$timestamp_now = (time() + ($mosConfig_offset*60*60)); //in [s] from January 1 1970 00:00:00 GMT (Unix Epoch) up to now (today)
    $timestamp_now = time(); //in [s] from January 1 1970 00:00:00 GMT (Unix Epoch) up to now (today)
    $timestamp_yesterday = ($timestamp_now - 24*60*60); //in [s] from January 1 1970 00:00:00 GMT (Unix Epoch) up to yesterday
	
    $present_day = date('d', $timestamp_now);
    $present_month = date('n', $timestamp_now);
    $present_year = date('Y', $timestamp_now);
	
	$previous_year = date('Y', mktime(0, 0, 0, date('m'), 1, date('Y')-1));
	
	$previous_month_first_day = '01';
	$previous_month_last_day = date('d', mktime(0, 0, 0, date('m'), 0, date('Y')));
	$previous_month_month = date('n', mktime(0, 0, 0, date('m')-1, 1, date('Y')));
	$previous_month_year = date('Y', mktime(0, 0, 0, date('m')-1, 1, date('Y')));
    	
    $yesterday_day = date('d', $timestamp_yesterday);
    $yesterday_month = date('m', $timestamp_yesterday);
    $yesterday_year = date('Y', $timestamp_yesterday);

    /** define Counters first: prefixes s -special, v -visits; p -page impressions; second: t-timestamp */
    $counter_def_arr = array(
       array('name'  => 'v_today', //counter : today's visits
			 'visitors_type' => _JS_DB_IPADD__TYPE_REGULAR_VISITOR,
			 'include_summarized' => 1 ,
			 'date_from' => $present_year.'-'.$present_month.'-'.$present_day,
			 'date_to' => $present_year.'-'.$present_month.'-'.$present_day),
       array('name'  => 'v_yesterday', // counter : yesterday's visits
			 'visitors_type' => _JS_DB_IPADD__TYPE_REGULAR_VISITOR,
			 'include_summarized' => 1 ,
			 'date_from' => $yesterday_year.'-'.$yesterday_month.'-'.$yesterday_day,
			 'date_to' => $yesterday_year.'-'.$yesterday_month.'-'.$yesterday_day),			 
       array('name'  => 'v_month', //counter : this month visits
			 'visitors_type' => _JS_DB_IPADD__TYPE_REGULAR_VISITOR,
			 'include_summarized' => 1 ,
			 'date_from' => $present_year.'-'.$present_month.'-'.'1',
			 'date_to' => $present_year.'-'.$present_month.'-'.$present_day),
       array('name'  => 'v_prev_month', //counter : previous month visits
			 'visitors_type' => _JS_DB_IPADD__TYPE_REGULAR_VISITOR,
			 'include_summarized' => 1 ,
			 'date_from' => $previous_month_year.'-'.$previous_month_month.'-'.$previous_month_first_day,
			 'date_to' => $previous_month_year.'-'.$previous_month_month.'-'.$previous_month_last_day),
       array('name'  => 'v_year', // counter : this year visits
			 'visitors_type' => _JS_DB_IPADD__TYPE_REGULAR_VISITOR,
			 'include_summarized' => 1 ,
			 'date_from' => $present_year.'-01-01',
			 'date_to' => $present_year.'-'.$present_month.'-'.$present_day),
       array('name'  => 'v_prev_year', // counter : previous year visits
			 'visitors_type' => _JS_DB_IPADD__TYPE_REGULAR_VISITOR,
			 'include_summarized' => 1 ,
			 'date_from' => $previous_year.'-01-01',
			 'date_to' => $previous_year.'-12-31'),			 
       array('name'  => 'v_total', // counter : total visits
			 'visitors_type' => _JS_DB_IPADD__TYPE_REGULAR_VISITOR,
			 'include_summarized' => 1 ,
			 'date_from' => '1970-01-01',
			 'date_to' => $present_year.'-'.$present_month.'-'.$present_day),
       array('name'  => 'v_maxaday', // counter : max visits per dat
	         'query' => 'SELECT SQL_BIG_RESULT COUNT(*) AS nbr_visitors, '
						. 'YEAR(w.visit_date) as Year, MONTH(w.visit_date) as Month, DAY(w.visit_date) as Day '
                        . 'FROM #__jstats_visits AS w '
                        . 'LEFT JOIN #__jstats_ipaddresses a ON (w.visitor_id=a.id) '
                        . 'WHERE a.type=1 '
                        . 'GROUP BY YEAR(w.visit_date), MONTH(w.visit_date), DAY(w.visit_date) '
                        . 'order by 1 DESC '
						. 'LIMIT 1 '),
       array('name'  => 'v_maxaday_day', // counter : month of max visits per day
	         'query' => 'SELECT SQL_BIG_RESULT COUNT(*) AS nbr_visitors, '
						. 'YEAR(w.visit_date) as Year, MONTH(w.visit_date) as Month, DAY(w.visit_date) as Day '
                        . 'FROM #__jstats_visits AS w '
                        . 'LEFT JOIN #__jstats_ipaddresses a ON (w.visitor_id=a.id) '
                        . 'WHERE a.type=1 '
                        . 'GROUP BY YEAR(w.visit_date), MONTH(w.visit_date), DAY(w.visit_date) '
                        . 'order by 1 DESC '
						. 'LIMIT 1 '),
       array('name'  => 'v_maxamonth', // counter : max visits per month
	         'query' => 'SELECT SQL_BIG_RESULT COUNT(*) AS nbr_visitors, YEAR(w.visit_date) as Year, MONTH(w.visit_date) as Month '
                        . 'FROM #__jstats_visits AS w '
                        . 'LEFT JOIN #__jstats_ipaddresses a ON (w.visitor_id=a.id) '
                        . 'WHERE a.type=1 '
                        . 'GROUP BY YEAR(w.visit_date), MONTH(w.visit_date) '
                        . 'order by 1 DESC '
						. 'LIMIT 1 '),
       array('name'  => 'v_maxamonth_month', //counter : month of max visits per month
	         'query' => 'SELECT SQL_BIG_RESULT COUNT(*) AS nbr_visitors, YEAR(w.visit_date) as Year, MONTH(w.visit_date) as Month '
                        . 'FROM #__jstats_visits AS w '
                        . 'LEFT JOIN #__jstats_ipaddresses a ON (w.visitor_id=a.id) '
                        . 'WHERE a.type=1 '
                        . 'GROUP BY YEAR(w.visit_date), MONTH(w.visit_date) '
                        . 'order by 1 DESC '
						. 'LIMIT 1 '),
       array('name'  => 'p_today', // counter : pages impressions today
			 'include_summarized' => 1 ,
			 'date_from' => $present_year.'-'.$present_month.'-'.$present_day,
			 'date_to' => $present_year.'-'.$present_month.'-'.$present_day),
       array('name'  => 'p_yesterday', // counter : pages impressions yesterday
			 'include_summarized' => 1 ,
			 'date_from' => $yesterday_year.'-'.$yesterday_month.'-'.$yesterday_day,
			 'date_to' => $yesterday_year.'-'.$yesterday_month.'-'.$yesterday_day),
       array('name'  => 'p_month', // counter : pages impressions this month
			 'include_summarized' => 1 ,
			 'date_from' => $present_year.'-'.$present_month.'-'.'1',
			 'date_to' => $present_year.'-'.$present_month.'-'.$present_day),
       array('name'  => 'p_total', // counter : pages impressions total
			 'include_summarized' => 1 ,
			 'date_from' => '1970-01-01',
			 'date_to' => $present_year.'-'.$present_month.'-'.$present_day),
       array('name'  => 'v_bots_today', //counter : today's bots visits
			 'visitors_type' => _JS_DB_IPADD__TYPE_BOT_VISITOR ,
			 'include_summarized' => 1 ,
			 'date_from' => $present_year.'-'.$present_month.'-'.$present_day,
			 'date_to' => $present_year.'-'.$present_month.'-'.$present_day),
       array('name'  => 's_date_since',
	         'query' => 'SELECT MIN(w.visit_date) FROM #__jstats_visits w')
     );

     return $counter_def_arr;
  }


  function getCounterResult( $counter )
  {
    $result = 0;

    $JSApiGeneral = new js_JSApiGeneral();
	$db =& JFactory::getDBO();

    switch( $counter['name'] )
    {
	  case 'v_today': //counter : today's visits
			$JSApiGeneral->getVisitorsNumber( $counter['visitors_type'], $counter['include_summarized'], $counter['date_from'], $counter['date_to'], $visitors_number_result );
			$result=$visitors_number_result;
	    break;

	  case 'v_yesterday': //counter : yesterday's visits
			$JSApiGeneral->getVisitorsNumber( $counter['visitors_type'], $counter['include_summarized'], $counter['date_from'], $counter['date_to'], $visitors_number_result );
			$result=$visitors_number_result;
	    break;

	  case 'v_month': //counter : this month visits
			$JSApiGeneral->getVisitorsNumber( $counter['visitors_type'], $counter['include_summarized'], $counter['date_from'], $counter['date_to'], $visitors_number_result );
			$result=$visitors_number_result;
	    break;

      case 'v_prev_month': //counter : previous month visits
			$JSApiGeneral->getVisitorsNumber( $counter['visitors_type'], $counter['include_summarized'], $counter['date_from'], $counter['date_to'], $visitors_number_result );
			$result=$visitors_number_result;
	    break;
		
	  case 'v_year':
			$JSApiGeneral->getVisitorsNumber( $counter['visitors_type'], $counter['include_summarized'], $counter['date_from'], $counter['date_to'], $visitors_number_result );
			$result=$visitors_number_result;
	    break;

	  case 'v_prev_year':
			$JSApiGeneral->getVisitorsNumber( $counter['visitors_type'], $counter['include_summarized'], $counter['date_from'], $counter['date_to'], $visitors_number_result );
			$result=$visitors_number_result;
	    break;
		
	  case 'v_total':
			$JSApiGeneral->getVisitorsNumber( $counter['visitors_type'], $counter['include_summarized'], $counter['date_from'], $counter['date_to'], $visitors_number_result );
			$result=$visitors_number_result;
		break;

      case 'v_maxaday':
			$db->setQuery( $counter['query'] );
			$result = $db->loadResult();
		break;

      case 'v_maxaday_day':
		  $db->setQuery( $counter['query'] );
		  $result_obj = $db->loadObject(); 
		  $result = $result_obj->Year . '-' . $result_obj->Month. '-' . $result_obj->Day;
        break;
		
      case 'v_maxamonth':
			$db->setQuery( $counter['query'] );
			$result = $db->loadResult();
        break;

      case 'v_maxamonth_month':
		  $db->setQuery( $counter['query'] );
		  $result_obj = $db->loadObject(); 
		  $result = $result_obj->Year . '-' . $result_obj->Month;
        break;

	  case 'p_today':
		  $JSApiGeneral->getPagesImpressionsSums( $counter['date_from'], $counter['date_to'], $counter['include_summarized'], $pages_impressions_sums );
			$result=$pages_impressions_sums->sum_all_pages_impressions;
	    break;				

	  case 'p_yesterday':
		  $JSApiGeneral->getPagesImpressionsSums( $counter['date_from'], $counter['date_to'], $counter['include_summarized'], $pages_impressions_sums );
			$result=$pages_impressions_sums->sum_all_pages_impressions;
	    break;				

	  case 'p_month':
		  $JSApiGeneral->getPagesImpressionsSums( $counter['date_from'], $counter['date_to'], $counter['include_summarized'], $pages_impressions_sums );
			$result=$pages_impressions_sums->sum_all_pages_impressions;
	    break;				

	  case 'p_total':
		  $JSApiGeneral->getPagesImpressionsSums( $counter['date_from'], $counter['date_to'], $counter['include_summarized'], $pages_impressions_sums );
			$result=$pages_impressions_sums->sum_all_pages_impressions;
	    break;				

		case 'v_bots_today': //counter : today's bots visits
			$JSApiGeneral->getVisitorsNumber( $counter['visitors_type'], $counter['include_summarized'], $counter['date_from'], $counter['date_to'], $visitors_number_result );
			$result=$visitors_number_result;
	    break;
		
      case 's_date_since':
			$db->setQuery( $counter['query'] );
			$result = $db->loadResult();
        break;

    }

    return $result;
  }



  function getCounterArrUnsorted( $params, &$counter_arr, &$order_arr )
  {
    $counter_def_arr = modJStatsCounters::getCountersDefinitions();

    foreach($counter_def_arr as $counter)
    {
      $counter_name = $counter['name'];
      if ($params->get($counter_name . '_enable') == 1)
      {//user select to publish that counter
          $label  = $params->get($counter_name . '_label', $counter_name);
          $number = modJStatsCounters::getCounterResult($counter);
          
		  if ($counter_name == 'v_total')
            $number = $number + (int)$params->get('v_total_offset', 0);
          if ($counter_name == 'v_maxaday_day')
          {
          	$format = $params->get('v_maxaday_day_format', 'Y-m-d');
          	$number = date($format, strtotime($number) );
          }
          if ($counter_name == 'v_maxamonth_month')
          {
          	$format = $params->get('v_maxamonth_month_format', 'Y-m');
          	$number = date($format, strtotime($number) );
          }
          
		  if ($counter_name == 'p_total')
          	$number = $number + (int)$params->get('p_total_offset', 0);

          if ($counter_name == 's_date_since')
          {
          	$format = $params->get('s_date_since_format', 'Y-m-d');
          	$number = date($format, strtotime($number) );
          }

          $counter_arr[$counter_name] = array( 'name' => $counter_name, 'label' => $label, 'number' => $number );
          $order_arr[$counter_name] = $params->get($counter_name . '_order', 99);
      }
    }
  }


  function sortCounterArr1Column( $counter_arr, $order_arr )
  {
    asort($order_arr);
    $counter_arr_sorted = array();
    foreach($order_arr as $key => $val)
      $counter_arr_sorted[$key] = $counter_arr[$key];

    return $counter_arr_sorted;
  }

  function sortCounterArr2Column( &$counter_arr_sorted )
  {
      if ( isset($counter_arr_sorted['p_today']) && isset($counter_arr_sorted['v_today']) )
      {
        $counter_arr_sorted['v_today']['p_number'] = $counter_arr_sorted['p_today']['number'];
        unset ($counter_arr_sorted['p_today']);
      }
      if ( isset($counter_arr_sorted['p_yesterday']) && isset($counter_arr_sorted['v_yesterday']) )
      {
        $counter_arr_sorted['v_yesterday']['p_number'] = $counter_arr_sorted['p_yesterday']['number'];
        unset ($counter_arr_sorted['p_yesterday']);
      }
      if ( isset($counter_arr_sorted['p_month']) && isset($counter_arr_sorted['v_month']) )
      {
        $counter_arr_sorted['v_month']['p_number'] = $counter_arr_sorted['p_month']['number'];
        unset ($counter_arr_sorted['p_month']);
      }
      if ( isset($counter_arr_sorted['p_total']) && isset($counter_arr_sorted['v_total']) )
      {
        $counter_arr_sorted['v_total']['p_number'] = $counter_arr_sorted['p_total']['number'];
        unset ($counter_arr_sorted['p_total']);
      }
  }


  function getCounterArr( $params )
  {
    $counter_arr = array();
    $order_arr = array();
    modJStatsCounters::getCounterArrUnsorted( $params, $counter_arr, $order_arr );

    $counter_arr_sorted = modJStatsCounters::sortCounterArr1Column( $counter_arr, $order_arr );

    $vis_type = $params->get('visualization_type');// 0 -1 column table
    if ( $vis_type == 1 )
        modJStatsCounters::sortCounterArr2Column( $counter_arr_sorted );

    unset($counter_arr);
    unset($order_arr);

    return $counter_arr_sorted;
  }
}

